package br.ufmg.dcc.paa.util;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.LinkedList;
import java.util.Map;

import br.ufmg.dcc.paa.collections.Instruction;
import br.ufmg.dcc.paa.collections.InstructionKind;

public class Parser {

    private static String ID = "([a-zA-Z]+\\w*)";
    private static String SPACES = "(\\s*)";
    
    private static Map<InstructionKind, String> patterns;
    static {
    	patterns = new HashMap<>();
        patterns.put(InstructionKind.BASE, ID + SPACES + "=" + SPACES + "&" + ID);
        patterns.put(InstructionKind.SIMPLE, ID + SPACES + "=" + SPACES + ID);
        patterns.put(InstructionKind.LOAD, ID + SPACES + "=" + SPACES + "\\*" + ID);
        patterns.put(InstructionKind.STORE, "\\*" + ID + SPACES + "=" + SPACES + ID);
    }
    
    private Parser() {}
    
    public static List<Instruction> parse(String fileName) throws IOException {
        List<String> lines = Util.readFromFile(fileName);
        List<Instruction> instructions = new LinkedList<Instruction>();
        Instruction i;
        for (String line : lines) {
            for (InstructionKind kind : patterns.keySet()) {
                if (line.matches(patterns.get(kind))) {
                	String[] variables = line.split("=");
                	i = new Instruction(kind, clean(variables[0]), clean(variables[1]));
                    instructions.add(i);
                    break;
                }
            }
        }
        return instructions;
    }

    private static String clean(String s) {
        return s.replace("*", "").replace("&", "").trim();
    }
	
}
